import 'dart:convert';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/a_elder/models/item_type_entity.dart';
import 'package:ls_work/a_yyt/models/pay_type_entity.dart';
import 'package:ls_work/a_yyt/models/sporadic_income_entity.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/click_item.dart';

import '../../util/flat_button.dart';

class AddHomeSporadicIncomePage extends StatefulWidget {
  final int? type;
  final ElderInfo? elderInfo;
  final VoidCallback? callBack;

  AddHomeSporadicIncomePage(
      {Key? key, this.type,  this.callBack, this.elderInfo});

  @override
  _AddHomeSporadicIncomePageState createState() =>
      _AddHomeSporadicIncomePageState();
}

class _AddHomeSporadicIncomePageState extends State<AddHomeSporadicIncomePage> {
  List<ItemTypeInfo> _itemTypeList = [];
  List<SporadicIncomeInfo> _chargeItemList = [];
  List<PayTypeInfo> _payTypeList = [];
  PayTypeInfo _payTypeInfo = PayTypeInfo();
  ItemTypeInfo _itemTypeInfo = ItemTypeInfo();
  SporadicIncomeInfo _chargeItemInfo = SporadicIncomeInfo();
  TextEditingController controller = TextEditingController(text: '1');
  TextEditingController _textFieldEditer = TextEditingController();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      fectItemType();
      fectPayTypeLList();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('新增零星收入'),
        elevation: 0.5,
      ),
      body: Stack(fit: StackFit.expand, children: <Widget>[
        SingleChildScrollView(
          padding: EdgeInsets.fromLTRB(20, 30, 30, 80),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              widget.elderInfo != null
                  ? Text.rich(TextSpan(children: [
                      TextSpan(
                        text: '         ${widget.elderInfo?.name ?? ''}：',
                        style: TextStyles.textGray18,
                      ),
                      TextSpan(
                        text: '${widget.elderInfo?.roomNo ?? ''}',
                        style: TextStyles.textDark18,
                      ),
                    ]))
                  : Container(),
              widget.elderInfo != null
                  ? SizedBox(
                      height: 32,
                    )
                  : SizedBox(),
              Text.rich(TextSpan(children: [
                TextSpan(
                  text: '     收费类型：',
                  style: TextStyles.textGray18,
                ),
                TextSpan(
                  text: widget.type == 0 ? '机构内收入' : '机构外收入',
                  style: TextStyles.textDark18,
                ),
              ])),
              Gaps.vGap16,
              ClickItem(
                title: '*项目类型：',
                titleStyle: TextStyles.textGray18,
                contentStyle: TextStyles.textDark18,
                content: '${_itemTypeInfo.name ?? ''}',
                onTap: _bottomItemTypeSheetAlert,
              ),
              Gaps.vGap16,
              ClickItem(
                title: '*收费项目：',
                titleStyle: TextStyles.textGray18,
                contentStyle: TextStyles.textDark18,
                content: '${_chargeItemInfo.name ?? ''}',
                onTap: _bottomChargeItemSheetAlert,
              ),
              Gaps.vGap16,
              Text.rich(TextSpan(children: [
                TextSpan(
                  text: '     费用项目：',
                  style: TextStyles.textGray18,
                ),
                TextSpan(
                  text: TextUtil.isEmpty(_chargeItemInfo.billingUnitName)
                      ? '${_chargeItemInfo.price ?? 0.0}元'
                      : '${_chargeItemInfo.price ?? 0.0}元/${_chargeItemInfo.billingUnitName}',
                  style: TextStyles.textDark18,
                ),
              ])),
              Gaps.vGap16,
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Text(
                    '     *使用数量：',
                    style: TextStyles.textGray18,
                  ),
                  Expanded(
                    child: Container(
                      height: 46,
                      padding: EdgeInsets.all(8),
                      color: Colours.bg_color,
                      child: TextField(
                        keyboardType: TextInputType.phone,
                        inputFormatters: [
                          FilteringTextInputFormatter.allow(RegExp("[0-9]"))
                        ],
                        controller: controller,
                        decoration: InputDecoration(
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              Gaps.vGap16,
              Text.rich(TextSpan(children: [
                TextSpan(
                  text: '     *费用合计：',
                  style: TextStyles.textGray18,
                ),
                TextSpan(
                  text: TextUtil.isEmpty(controller.text)
                      ? '0.0'
                      : '${int.parse(controller.text ?? '0.0') * (_chargeItemInfo.price ?? 0.0)}',
                  style: TextStyles.textDark18,
                ),
              ])),
              Gaps.vGap16,
              ClickItem(
                title: '*支付方式：',
                titleStyle: TextStyles.textGray18,
                contentStyle: TextStyles.textDark18,
                content: '${_payTypeInfo.value ?? ''}',
                onTap: widget.type == 0 ? null : _bottomPayypeSheetAlert,
              ),
              Gaps.vGap15,
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    '   备注',
                    style: TextStyles.textGray18,
                  ),
                  Container(
                    padding: EdgeInsets.fromLTRB(20, 0, 20, 20),
                    alignment: Alignment.topLeft,
                    height: 150,
                    width: ScreenUtil.getScreenW(context) - 100,
                    child: TextField(
                      controller: _textFieldEditer,
                      maxLines: 5,
                      maxLength: 150,
                      autofocus: false,
                      decoration: InputDecoration(
                        hintText: "请输入内容",
                        hintMaxLines: 20,
                        fillColor: Colours.bg_color,
                        filled: true,
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
        Positioned(
          bottom: 30,
          left: 30,
          right: 30,
          child: SizedBox(
            width: ScreenUtil.getScreenW(context),
            height: 50,
            child: FlatsButton(
              color: Colors.blue,
              highlightColor: Colors.blue[700]!,
              child: Text("提交"),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0)),
              onPressed: _send,
            ),
          ),
        ),
      ]),
    );
  }

  ///提交
  void _send() {
    if (TextUtil.isEmpty(_chargeItemInfo.name)) {
      Toast.show('请选收费项目');
      return;
    }
    if (TextUtil.isEmpty(_itemTypeInfo.name)) {
      Toast.show('请选择项目类型');
      return;
    }
    if (TextUtil.isEmpty(controller.text)) {
      Toast.show('请输入使用数量');
      return;
    }
    Map<String, dynamic> map = {
      'expenseItemId': _chargeItemInfo.id,
      'num': int.parse(controller.text),
      'price': _chargeItemInfo.price,
      'money': _chargeItemInfo.price != null
          ? _chargeItemInfo.price! * int.parse(controller.text)
          : 0.0,
      'payType': _payTypeInfo.code,
      'source': widget.type,
    };
    if (!TextUtil.isEmpty(_textFieldEditer.text)) {
      map['remark'] = _textFieldEditer.text;
    }
    if (widget.type == 0) {
      map['elderHumanId'] = widget.elderInfo?.id;
    }

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.expenseMealsCreate,
            data: {'jsonStr': jsonEncode(map)},options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if (widget.type == 1){
            if(widget.callBack!=null){
              widget.callBack!();
            }
          }

          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///项目类型
  void fectItemType() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.findExpenseTypeList, data: requestParams({'bizType': 40}))
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            ItemTypeEntity model = ItemTypeEntity.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              _itemTypeList = model.rows??[];
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///收费项目
  void fectChargeItem() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    var map = {
      'expenseTypeId': _itemTypeInfo.id,
      'bizType': _itemTypeInfo.bizType,
      'branchId': _itemTypeInfo.branchId,
    };
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.findExpenseItemList}?${requestParams(map)}')
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            SporadicIncomeEntity model =
                SporadicIncomeEntity.fromJson(map['data']);
            if ((model.rows ?? []).length > 0) {
              _chargeItemList = model.rows ?? [];
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///支付方式
  void fectPayTypeLList() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    var map = {'source': widget.type};
    HttpUtil.instance
        .getDio()
        .post(HttpApi.findMealsPayTypeList,
            data: {'jsonStr': jsonEncode(map)},options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            PayTypeEntity model = PayTypeEntity.fromJson(map['data']);
            if ((model.options??[]).length > 0) {
              setState(() {
                _payTypeList = model.options??[];
                _payTypeInfo = model.options!.first;
              });
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///项目类型列表
  _bottomChargeItemSheetAlert() {
    if (_itemTypeInfo.id == null) {
      Toast.show('请选择项目类型');
      return;
    }
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return Container(
          width: double.infinity,
          height: ScreenUtil.getScreenH(context) * 2 / 3,
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: _chargeItemList.map((f) {
                return ListTile(
                  leading: Text(f.name??""),
                  title: Text(
                    TextUtil.isEmpty(f.billingUnitName)
                        ? '${f.price ?? 0.0}元'
                        : '${f.price ?? 0.0}元/${f.billingUnitName}',
                  ),
                  onTap: () {
                    setState(() {
                      _chargeItemInfo = f;
                    });
                    Navigator.pop(context);
                  },
                );
              }).toList(),
            ),
          ),
        );
      },
    );
  }

  ///收费项目列表
  _bottomItemTypeSheetAlert() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return Container(
          width: double.infinity,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: _itemTypeList.map((f) {
              return ListTile(
                title: Text(f.name??""),
                onTap: () {
                  setState(() {
                    _itemTypeInfo = f;
                    fectChargeItem();
                  });
                  Navigator.pop(context);
                },
              );
            }).toList(),
          ),
        );
      },
    );
  }

  ///支付方式
  void _bottomPayypeSheetAlert() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return Container(
          width: double.infinity,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: _payTypeList.map((f) {
              return ListTile(
                title: Text(f.value??""),
                onTap: () {
                  setState(() {
                    _payTypeInfo = f;
                  });
                  Navigator.pop(context);
                },
              );
            }).toList(),
          ),
        );
      },
    );
  }
}
